package com.ysd.lis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2021-10-08
 */
@Service
@Slf4j
public class SysBasDictServiceImpl extends ServiceImpl<SysBasDictMapper, SysBasDict> implements SysBasDictService {
    @Autowired
    SysBasDictMapper sysBasDictMapper;
    @Autowired
    SysBasDictService sysBasDictService;
    @Autowired
    SysBasDictDetailMapper sysBasDictDetailMapper;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    SysBasDictTableMapper sysBasDictTableMapper;

    @Autowired
    SysBasDictTableService sysBasDictTableService;
    @Autowired
    SysBasDictTableFieldMapper sysBasDictTableFieldMapper;

    @Autowired
    SysBasDictTableFieldService sysBasDictTableFieldService;
    @Autowired
    SysBasDictTypeMapper sysBasDictTypeMapper;

    @Autowired
    SysBasDictTypeService sysBasDictTypeService;

    @Override
    public Result findDictPageList(CommonPageDto pageParam) {
        Page<SysBasDict> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<SysBasDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysBasDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysBasDict::getName, pageParam.getSeachValue())
                    .or().like(SysBasDict::getCode, pageParam.getSeachValue()));
        }
        if (StringUtils.isNotBlank(pageParam.getPid())) {
            lambdaQueryWrapper.eq(SysBasDict::getPid, pageParam.getPid());
        }
        if (null != pageParam.getGrade()) {
            lambdaQueryWrapper.eq(SysBasDict::getGrade, pageParam.getGrade());
        }
        lambdaQueryWrapper.orderByAsc(SysBasDict::getSx);
        Page<SysBasDict> userPage = sysBasDictMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", userPage);
    }

    @Override
    public Result findDictList(CommonPageDto pageParam) {
        LambdaQueryWrapper<SysBasDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysBasDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysBasDict::getName, pageParam.getSeachValue())
                    .or().like(SysBasDict::getCode, pageParam.getSeachValue()));
        }
        if (null != pageParam.getGrade()) {
            lambdaQueryWrapper.eq(SysBasDict::getGrade, pageParam.getGrade());
        }
        if (StringUtils.isNotBlank(pageParam.getPid())) {
            lambdaQueryWrapper.eq(SysBasDict::getPid, pageParam.getPid());
        }
        lambdaQueryWrapper.orderByAsc(SysBasDict::getSx);
        List<SysBasDict> dictList = sysBasDictMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(dictList)) {
            List<String> pIds = dictList.stream().map(SysBasDict::getPid).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(pIds)) {
                List<SysBasDict> parentDictList = this.listByIds(pIds);
                if (CollectionUtils.isNotEmpty(parentDictList)) {
                    for (SysBasDict dict : dictList) {
                        Optional<SysBasDict> any = parentDictList.stream().filter(a -> a.getId().equals(dict.getPid())).findAny();
                        if (any.isPresent()) {
                            SysBasDict parentDict = any.get();
                            dict.setIsParentEdit(parentDict.getIsEdit());
                        }
                    }
                }
            }
        }
        return Result.succ(1, "查询成功", dictList);
    }

    @Override
    public Result findDictTypeAndDictList(CommonPageDto pageParam) {
        LambdaQueryWrapper<SysBasDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysBasDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysBasDict::getName, pageParam.getSeachValue())
                    .or().like(SysBasDict::getCode, pageParam.getSeachValue()));
        }
        if (null != pageParam.getGrade()) {
            lambdaQueryWrapper.eq(SysBasDict::getGrade, pageParam.getGrade());
        }
        if (StringUtils.isNotBlank(pageParam.getPid())) {
            lambdaQueryWrapper.eq(SysBasDict::getPid, pageParam.getPid());
        }
        lambdaQueryWrapper.orderByAsc(SysBasDict::getSx);
        List<SysBasDict> dictList = sysBasDictMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(dictList)) {
            List<String> pIds = dictList.stream().map(SysBasDict::getPid).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(pIds)) {
                List<SysBasDictType> typeList1 = sysBasDictTypeMapper.selectBatchIds(pIds);
                List<SysBasDictType> typeList = typeList1.stream().sorted(comparing(l -> l.getSx())).collect(Collectors.toList());

                if (CollectionUtils.isNotEmpty(typeList)) {
                    for (SysBasDictType type : typeList) {
                        List<SysBasDict> collect = dictList.stream().filter(a -> a.getPid().equals(type.getId())).collect(Collectors.toList());
                        type.setDictList(collect);
                    }
                    return Result.succ(1, "查询成功", typeList);
                }
            }
        }
        return Result.succ(1, "查询成功", null);
    }

    @Override
    public Result findDictAndDetailList(CommonPageDto pageParam) {
        Map<String, Object> retrunMap = new HashMap<>();
        LambdaQueryWrapper<SysBasDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysBasDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysBasDict::getName, pageParam.getSeachValue())
                    .or().like(SysBasDict::getCode, pageParam.getSeachValue()));
        }
        if (null != pageParam.getGrade()) {
            lambdaQueryWrapper.eq(SysBasDict::getGrade, pageParam.getGrade());
        }
        if (StringUtils.isNotBlank(pageParam.getPid())) {
            lambdaQueryWrapper.eq(SysBasDict::getPid, pageParam.getPid());
        }
        if (StringUtils.isNotBlank(pageParam.getPCode())){
            List<SysBasDict> sysBasDicts = sysBasDictMapper.selectList(new LambdaQueryWrapper<SysBasDict>().eq(SysBasDict::getCode, pageParam.getPCode()).eq(SysBasDict::getDelFlag, 0));
            if (CollectionUtils.isNotEmpty(sysBasDicts)){
                pageParam.setPid(sysBasDicts.get(0).getId());
                lambdaQueryWrapper.eq(SysBasDict::getPid, pageParam.getPid());
            }else {
                retrunMap.put("dictList", new ArrayList<>());
                retrunMap.put("detailList", new ArrayList<>());
                return Result.succ(1, "查询成功", retrunMap);
            }
        }
        lambdaQueryWrapper.orderByAsc(SysBasDict::getSx);
        List<SysBasDict> dictList = sysBasDictMapper.selectList(lambdaQueryWrapper);
        retrunMap.put("dictList", dictList);

        //查询字典值
        MPJLambdaWrapper<SysBasDictDetail> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(SysBasDictDetail.class)
                .selectAs("b", SysBasDict::getIsEdit, SysBasDictDetail::getIsParentEdit)
                .leftJoin(SysBasDict.class, "a", SysBasDict::getId, SysBasDictDetail::getPid)
                .leftJoin(SysBasDict.class, "b", SysBasDict::getId, SysBasDict::getPid)

                .eq(SysBasDict::getPid, pageParam.getPid())
                .eq(SysBasDictDetail::getDelFlag, 0)
                .orderByAsc(SysBasDictDetail::getSx);

        List<Map<String, Object>> list = new ArrayList<>();
        List<SysBasDictDetail> detailList = sysBasDictDetailMapper.selectList(queryWrapper);
        Map<String, List<SysBasDictDetail>> collect = detailList.stream().collect(Collectors.groupingBy(SysBasDictDetail::getCommonId));
        Set<String> commonIds = collect.keySet();
        for (String commonId : commonIds) {
            List<SysBasDictDetail> dicts = collect.get(commonId);
            Map<String, Object> map = new HashMap<>();
            map.put("commonId", commonId);
            for (SysBasDictDetail dictitem : dicts) {
                map.put(dictitem.getCode(), dictitem.getValue());
                map.put("sx", dictitem.getSx());
                map.put("isParentEdit", dictitem.getIsParentEdit());
                map.put("grade", dictitem.getGrade());
            }
            list.add(map);
        }
        List<Map<String, Object>> no = list.stream().sorted(comparing(l -> (Integer) l.get("sx"))).collect(Collectors.toList());
        retrunMap.put("detailList", no);
        return Result.succ(1, "查询成功", retrunMap);
    }

    @Override
    public Result findDictListByType(CommonPageDto pageParam) {
        MPJLambdaWrapper<SysBasDict> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(SysBasDict.class)
                .leftJoin(SysBasDictType.class, SysBasDictType::getId, SysBasDict::getPid)
                .eq(SysBasDictType::getCode, pageParam.getCode());
        if (null != pageParam.getGrade()) {
            queryWrapper.eq(SysBasDict::getGrade, pageParam.getGrade());
        }
        queryWrapper.eq(SysBasDict::getDelFlag, 0)
                .orderByAsc(SysBasDict::getCreateTime);
        List<SysBasDict> dictList = sysBasDictMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", dictList);
    }

    @Override
    public Result addDict(SysBasDict dict) {
        if(0 == dict.getGrade()){
            //添加字典时先判断是否已经存在此编号的字典
            LambdaQueryWrapper<SysBasDict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBasDict::getCode, dict.getCode())
                    .eq(SysBasDict::getGrade, dict.getGrade())
                    .eq(SysBasDict::getDelFlag, 0);
            int count = this.count(queryWrapper);
            if (count > 0) {
                return Result.fail("此编号已存在，添加失败！");
            }
        }
        int insert = sysBasDictMapper.insert(dict);
        if (insert > 0) {
            Integer grade = dict.getGrade();
            if (grade == 0) {
                //添加默认增加一个字段：是否可删除
                SysBasDict addDict = new SysBasDict();
                addDict.setGrade(1);
                addDict.setName("是否删改");
                addDict.setCode("isEdit");
                addDict.setPid(dict.getId());
                addDict.setOrgId(dict.getOrgId());
                addDict.setSx(99);
                sysBasDictMapper.insert(addDict);
            }
            return Result.succ(1, "添加成功", dict);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editDict(SysBasDict dict) {
        if(0 == dict.getGrade()){
            //添加字典时先判断是否已经存在此编号的字典
            LambdaQueryWrapper<SysBasDict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBasDict::getCode, dict.getCode())
                    .eq(SysBasDict::getGrade, dict.getGrade())
                    .ne(SysBasDict::getId, dict.getId())
                    .eq(SysBasDict::getDelFlag, 0);
            int count = this.count(queryWrapper);
            if (count > 0) {
                return Result.fail("此编号已存在，添加失败！");
            }
        }
        int updateById = sysBasDictMapper.updateById(dict);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", dict);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result deleteDict(SysBasDict dict) {
        Integer grade = dict.getGrade();
        if (grade == 0) {
            //查询本表中的chilern
            LambdaQueryWrapper<SysBasDict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBasDict::getPid, dict.getId()).eq(SysBasDict::getDelFlag, 0);
            Integer integer = sysBasDictMapper.selectCount(queryWrapper);
            if (integer > 0) {
                return Result.fail(400, "该字典有字典值，不能删除字典", "");
            }
        } else if (grade == 1) {
            //查询子表中的chilern
            LambdaQueryWrapper<SysBasDictDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBasDictDetail::getPid, dict.getId()).eq(SysBasDictDetail::getDelFlag, 0);
            Integer integer = sysBasDictDetailMapper.selectCount(queryWrapper);
            if (integer > 0) {
                return Result.fail(400, "该字典有字典值，不能删除字典属性", "");
            }
        }
        int deleteById = sysBasDictMapper.deleteById(dict.getId());
        if (deleteById > 0) {
            return Result.succ(1, "删除成功", "");
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result copyDictByOrgId(OrganizationDTO organizationDTO) {
        String letter = AlphabetArray.Alphabet[organizationDTO.getOrgIndex()];
        sysBasDictMapper.delete(new LambdaQueryWrapper<SysBasDict>().eq(SysBasDict::getOrgId, organizationDTO.getGoalOrgId()));
        sysBasDictDetailMapper.delete(new LambdaQueryWrapper<SysBasDictDetail>().eq(SysBasDictDetail::getOrgId, organizationDTO.getGoalOrgId()));
        sysBasDictTableMapper.delete(new LambdaQueryWrapper<SysBasDictTable>().eq(SysBasDictTable::getOrgId, organizationDTO.getGoalOrgId()));
        sysBasDictTableFieldMapper.delete(new LambdaQueryWrapper<SysBasDictTableField>().eq(SysBasDictTableField::getOrgId, organizationDTO.getGoalOrgId()));
        sysBasDictTypeMapper.delete(new LambdaQueryWrapper<SysBasDictType>().eq(SysBasDictType::getOrgId, organizationDTO.getGoalOrgId()));

        List<SysBasDict> sysBasDicts = sysBasDictMapper.selectList(new LambdaQueryWrapper<SysBasDict>().eq(SysBasDict::getDelFlag, 0).eq(SysBasDict::getOrgId, organizationDTO.getSourceOrgId()));
        for (SysBasDict sysBasDict : sysBasDicts) {
            sysBasDict.setId(letter + sysBasDict.getId().substring(letter.length()));
            if (sysBasDict.getPid() != null) {
                sysBasDict.setPid(letter + sysBasDict.getPid().substring(letter.length()));
            }
            sysBasDict.setOrgId(organizationDTO.getGoalOrgId());
        }
        List<SysBasDictDetail> sysBasDictDetails = sysBasDictDetailMapper.selectList(new LambdaQueryWrapper<SysBasDictDetail>().eq(SysBasDictDetail::getDelFlag, 0).eq(SysBasDictDetail::getOrgId, organizationDTO.getSourceOrgId()));
        for (SysBasDictDetail sysBasDictDetail : sysBasDictDetails) {
            sysBasDictDetail.setId(letter + sysBasDictDetail.getId().substring(letter.length()));
            if (sysBasDictDetail.getPid() != null) {
                sysBasDictDetail.setPid(letter + sysBasDictDetail.getPid().substring(letter.length()));
            }
            sysBasDictDetail.setOrgId(organizationDTO.getGoalOrgId());
        }
        List<SysBasDictTable> sysBasDictTables = sysBasDictTableMapper.selectList(new LambdaQueryWrapper<SysBasDictTable>().eq(SysBasDictTable::getDelFlag, 0).eq(SysBasDictTable::getOrgId, organizationDTO.getSourceOrgId()));
        for (SysBasDictTable sysBasDictTable : sysBasDictTables) {
            sysBasDictTable.setId(letter + sysBasDictTable.getId().substring(letter.length()));
            sysBasDictTable.setOrgId(organizationDTO.getGoalOrgId());
        }
        List<SysBasDictTableField> sysBasDictTableFields = sysBasDictTableFieldMapper.selectList(new LambdaQueryWrapper<SysBasDictTableField>().eq(SysBasDictTableField::getDelFlag, 0).eq(SysBasDictTableField::getOrgId, organizationDTO.getSourceOrgId()));
        for (SysBasDictTableField sysBasDictTableField : sysBasDictTableFields) {
            sysBasDictTableField.setId(letter + sysBasDictTableField.getId().substring(letter.length()));
            if (sysBasDictTableField.getPid() != null) {
                sysBasDictTableField.setPid(letter + sysBasDictTableField.getPid().substring(letter.length()));
            }
            sysBasDictTableField.setOrgId(organizationDTO.getGoalOrgId());
        }
        List<SysBasDictType> typeList = sysBasDictTypeMapper.selectList(new LambdaQueryWrapper<SysBasDictType>().eq(SysBasDictType::getDelFlag, 0).eq(SysBasDictType::getOrgId, organizationDTO.getSourceOrgId()));
        for (SysBasDictType dictType : typeList) {
            dictType.setId(letter + dictType.getId().substring(letter.length()));
            if (dictType.getPid() != null&& !"0".equals(dictType.getPid())) {
                dictType.setPid(letter + dictType.getPid().substring(letter.length()));
            }
            dictType.setOrgId(organizationDTO.getGoalOrgId());
        }
        sysBasDictService.saveBatch(sysBasDicts);
        sysBasDictDetailService.saveBatch(sysBasDictDetails);
        sysBasDictTableService.saveBatch(sysBasDictTables);
        sysBasDictTableFieldService.saveBatch(sysBasDictTableFields);
        sysBasDictTypeService.saveBatch(typeList);
        return Result.succ("操作成功");
    }


}
